<template>
  <div class="page-container online-users-container">
    <div class="page-title">
      在线用户管理
    </div>
    
    <div class="action-bar">
      <span class="data-statistics">
        <el-tag type="primary" effect="plain" round><el-icon><User /></el-icon> 在线用户数: {{ onlineUsers.length }}</el-tag>
      </span>
      
      <el-button type="primary" @click="fetchOnlineUsers" class="refresh-button">
        <el-icon><Refresh /></el-icon> 刷新列表
      </el-button>
    </div>
    
    <!-- 在线用户列表 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="onlineUsers"
        border
        style="width: 100%"
        :stripe="true"
        :highlight-current-row="true"
        empty-text="暂无在线用户"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="scope">
            <el-tag 
              :type="scope.row.role === 'admin' ? 'danger' : 'success'"
              effect="plain"
            >
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="登录时间" width="180" align="center" />
        <el-table-column prop="loginIp" label="登录IP" width="150" align="center" />
        <el-table-column prop="browser" label="浏览器" width="180" align="center" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-tooltip
              :content="scope.row.id === currentUserId ? '不能将自己踢下线' : '强制该用户下线'" 
              placement="top"
            >
              <el-button 
                size="small" 
                type="danger" 
                plain
                @click="handleForceLogout(scope.row)"
                :disabled="scope.row.id === currentUserId"
              >
                <el-icon><CircleClose /></el-icon> 强制下线
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, CircleClose, User } from '@element-plus/icons-vue'
import { getOnlineUsers, forceLogout } from '@/api/session'
import { useUserStore } from '@/store/user'

// 用户存储
const userStore = useUserStore()
// 当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id || 0)

// 在线用户列表数据
const onlineUsers = ref([])
const loading = ref(false)

// 获取在线用户列表
const fetchOnlineUsers = async () => {
  loading.value = true
  try {
    const res = await getOnlineUsers()
    console.log('在线用户API响应:', res.data)
    
    // 保存数据
    onlineUsers.value = res.data || []
    
    console.log('获取到的在线用户列表:', onlineUsers.value)
  } catch (error) {
    console.error('获取在线用户列表失败', error)
    ElMessage.error('获取在线用户列表失败')
  } finally {
    loading.value = false
  }
}

// 强制用户下线
const handleForceLogout = (row) => {
  // 不允许踢自己下线
  if (row.id === currentUserId.value) {
    ElMessage.warning('不能将自己踢下线')
    return
  }
  
  ElMessageBox.confirm(
    `确定要将用户 "${row.username}" 强制下线吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log('强制用户下线ID:', row.id)
      const res = await forceLogout(row.id)
      console.log('强制下线响应:', res)
      
      ElMessage.success('用户已被强制下线')
      // 重新获取在线用户列表
      fetchOnlineUsers()
    } catch (error) {
      console.error('强制下线失败', error)
      ElMessage.error('强制下线失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    console.log('用户取消操作')
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchOnlineUsers()
})
</script>

<style scoped>
.online-users-container {
  min-height: calc(100vh - 130px);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.data-statistics {
  font-size: 14px;
}

.data-statistics .el-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.data-statistics .el-icon {
  margin-right: 5px;
}

.data-statistics :deep(.el-tag--primary) {
  background-color: rgba(94, 92, 230, 0.1);
  border-color: rgba(94, 92, 230, 0.2);
  color: #5e5ce6;
}

.refresh-button {
  background: #5e5ce6;
  border-color: #5e5ce6;
}

.refresh-button:hover {
  background: #6b69e3;
  border-color: #6b69e3;
}

@media screen and (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .refresh-button {
    width: 100%;
  }
}
</style> 